//+------------------------------------------------------------------+
//|                                                   7号_原策略+新策略.mq4 |
//|                        Copyright 2021, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2021, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

enum opentime
  {
   A = 1,//开单时区模式
   B = 2,//开单时间间距(秒)模式
   C = 3,//不延迟模式
  };
extern string 以下是原策略="===============================";
extern double Money=0  ;              //浮亏多少启用第二参数
extern int   FirstStep=20  ;         //首单距离
extern int   MinDistance=40  ;       //最小距离
extern int   TwoMinDistance=240  ;    //第二最小距离
extern int   StepTrallOrders=5  ;     //挂单追踪点数
extern int   Step=50  ;              //补单间距
extern int   TwoStep=50  ;           //第二补单间距
extern  opentime  OpenMode=3  ;
extern  ENUM_TIMEFRAMES  TimeZone=1  ;//开单时区
extern int   sleep=30  ;              //开单时间间距(秒)
extern double lot=0.01  ;             //起始手数
extern double PlusLot=0  ;            //累加手数
extern double K_Lot=1.2  ;            //倍率
extern double StopProfit=2  ;         //单边平仓金额
extern int   MaxSpread=32  ;          //点差限制
extern int   Magic=9453  ;

extern string 以下是新策略="===============================";

input  double 首单手数=1.1;
input  double 顺势加仓倍数=1.3;
input  double 逆势加仓倍数=1.5;
input  int    顺势加仓间距=100;
input  int    逆势加仓间距=200;
input  double 顺势单次最大建仓手数=10;
input  double 逆势单次最大建仓手数=10;
input  int    多空最大持仓次数=100;
input  double 一边与另一边手数差大于N补仓=0.3;
input  double 该魔术码的货币亏损金额=10000;
input  int    魔术码金额平仓后EA暂停N小时=1;
input double  账户亏损金额超限全清仓=9000;
input double  账户亏损比例超限全清仓=90;                  
input int     自定义赠金=0;
input  double 多空总赢利金额平仓=100;
input  double 单向赢利多少金额对冲反向=25;
input  double 对冲反向保留差额N美金=10;
input ENUM_TIMEFRAMES   均线角度的时间周期（current代表图表周期） = PERIOD_M5;
input int               均线角度的均线参数 = 3;



                    
datetime  barcontronl = 0;
bool      buyonoff = true;
bool      sellonoff = true;
bool      buylossthansell = false;
bool      sellllossthanbuy = false;
int       ping=0;


   double      sellprofit;
   double      buyprofit;
   double      buyTTlots;
   double      sellTTlots;
   int         buyordercount;
   int         sellorderscount;
   int         buystopcount;
   int         sellstopcount;
   int         buystopticket;
   int         sellstopticket;
   double      minbuyprice;
   double      maxbuyprice;
   double      minsellprice;
   double      maxsellprice;
   double      buystopprice;
   double      sellstopprice;
   double      sellcost;
   double      buycost;
   double      buypriceaverage;
   double      sellpriceaverage;
   double      price;
   double      lots;
   int         count1;
   string      myspread;
   string      lever;
   double      checkprofit;
   bool        UseSetp;

   double      Totalprofit;

//----------------------------
   int        buySScount;
   int        count2;
   int        sellSScount;
   int        count3;
   int        buySScount1;
   int        count4;
   int        sellSScount1;
   double     tempbuylots;
   double     tempbuyprofit;
   int        count6;
   double     tempselllots;
   double     tempsellprofit;
   int        count7;
   int        color1;
   int        color2;
   int        color3;
   
   
   
   
   
   
   
   
   
   
int    AllBuy=0,AllSell=0;
int    新策略_AllVol=0,新策略_多=0,新策略_空=0;
double BuyHighest=0,BuyLowest=0,SellHighest=0,SellLowest=0;
int    Buyshun=0,Buyni=0,Sellshun=0,Sellni=0;
double minlot,maxlot;
double AllBuyLots=0,AllSellLots=0;
double All_yk=0;
double Buyyl=0,Sellyl=0;
datetime buytime,selltime;

datetime  魔术码金额平仓时间=0;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   minlot=MarketInfo(Symbol(), MODE_MINLOT);  
   maxlot=MarketInfo(Symbol(), MODE_MAXLOT);
   if(FirstStep < (MathMax(MarketInfo(Symbol(),MODE_FREEZELEVEL),MarketInfo(Symbol(),MODE_STOPLEVEL)) + 1))
     {
      FirstStep = (int)(MathMax(MarketInfo(Symbol(),MODE_FREEZELEVEL),MarketInfo(Symbol(),MODE_STOPLEVEL)) + 1) ;
     }
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
  if(TimeCurrent()-魔术码金额平仓时间>=魔术码金额平仓后EA暂停N小时*3600)
    {
    if(pingcang())  kaicang();
    yuancelue();
    }
  }
//+------------------------------------------------------------------+
void close_对冲(int type)
  {
  double yl=0;
  if(type==1) yl=Buyyl;
  if(type==0) yl=Sellyl;
  if(OrdersTotal()>0)  
    {
    for(int k=0;k<=OrdersTotal()-1;k++)
      {
      if(OrderSelect(k,SELECT_BY_POS,MODE_TRADES)==true)  
        {
        if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic)
          {
          if(type==1)
            {
            if(OrderType()==OP_BUY)  
              {
              if(OrderClose(OrderTicket(),OrderLots(),Bid,500)) k--;
              else
                {
                Print("订单号为：",OrderTicket(),"的多单平仓失败",iGetErrorInf0());
                }
              }
            if(OrderType()==2 || OrderType()==4)
              {
              if(OrderDelete(OrderTicket()))
                {
                Print("订单号为：",OrderTicket(),"的挂单删除成功 ");
                }
              else
                {
                Print("订单号为：",OrderTicket(),"的挂单删除失败 ",iGetErrorInf0());
                }
              }
            }
          if(type==0)
            {
            if(OrderType()==OP_SELL)
              {
              if(OrderClose(OrderTicket(),OrderLots(),Ask,500)) k--;
              else
                {
                Print("订单号为：",OrderTicket(),"的空单平仓失败",iGetErrorInf0());
                }
              }
            if(OrderType()==3 || OrderType()==5)
              {
              if(OrderDelete(OrderTicket()))
                {
                Print("订单号为：",OrderTicket(),"的挂单删除成功 ");
                }
              else
                {
                Print("订单号为：",OrderTicket(),"的挂单删除失败 ",iGetErrorInf0());
                }
              }
            }
          }
        }
      }
    }
  if(OrdersTotal()>0)
    {
    for(int k=OrdersTotal()-1;k>=0;k--)
      {   
      if(type==1)
        {
        double 盈亏=0;double 手数=0;
        int tic=price_tic(盈亏,手数,1,Magic);
        if(tic==0) break;
        if(盈亏<0 && yl>0)
          {
          if(yl+盈亏>对冲反向保留差额N美金)
            {
            yl+=盈亏;
            close_tic(tic);
            }
          else
            {
            double 比例=MathAbs((yl-对冲反向保留差额N美金)/盈亏);
            double 平仓手数=int((手数*比例)/minlot)*minlot;
            if(平仓手数<minlot) return;
            if(平仓手数>maxlot) 平仓手数=maxlot;  
            if(OrderClose(tic,平仓手数,Ask,500)) return;
            return;
            }
          }
        }
      if(type==0)
        {
        double 盈亏=0;double 手数=0;
        int tic=price_tic(盈亏,手数,0,Magic);
        if(tic==0) break;
        if(盈亏<0 && yl>0)
          {
          if(yl+盈亏>对冲反向保留差额N美金)
            {
            yl+=盈亏;
            close_tic(tic);
            }
          else
            {
            double 比例=MathAbs((yl-对冲反向保留差额N美金)/盈亏);
            double 平仓手数=int((手数*比例)/minlot)*minlot;
            if(平仓手数<minlot) return;
            if(平仓手数>maxlot) 平仓手数=maxlot;  
            if(OrderClose(tic,平仓手数,Bid,500)) return;
            return;
            }
          }
        }
      }
    }
  //if(OrdersTotal()>0)  
  //  {
  //  for(int k=0;k<=OrdersTotal()-1;k++)
  //    {
  //    if(OrderSelect(k,SELECT_BY_POS,MODE_TRADES)==true)  
  //      {
  //      if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic)
  //        {
  //        if(type==1)
  //          {
  //          if(OrderType()==OP_SELL)  
  //            {
  //            if(OrderProfit()+OrderSwap()+OrderCommission()<0)
  //              {
  //              if(yl+OrderProfit()+OrderSwap()+OrderCommission()>0)
  //                {
  //                yl+=(OrderProfit()+OrderSwap()+OrderCommission());
  //                if(OrderClose(OrderTicket(),OrderLots(),Ask,500)) k--;
  //                else
  //                  {
  //                  Print("订单号为：",OrderTicket(),"的空单平仓失败",iGetErrorInf0());
  //                  }
  //                }
  //              else
  //                {
  //                double 比例=MathAbs(yl/(OrderProfit()+OrderSwap()+OrderCommission()));
  //                double 平仓手数=MathRound((OrderLots()*比例)/minlot)*minlot;
  //                if(平仓手数<minlot) return;
  //                if(平仓手数>maxlot) 平仓手数=maxlot;  
  //                if(OrderClose(OrderTicket(),平仓手数,Ask,500)) return;
  //                return;
  //                }
  //              }
  //            }
  //          }
  //        if(type==0)
  //          {
  //          if(OrderType()==OP_BUY)  
  //            {
  //            if(OrderProfit()+OrderSwap()+OrderCommission()<0)
  //              {
  //              if(yl+OrderProfit()+OrderSwap()+OrderCommission()>0)
  //                {
  //                yl+=(OrderProfit()+OrderSwap()+OrderCommission());
  //                if(OrderClose(OrderTicket(),OrderLots(),Bid,500)) k--;
  //                else
  //                  {
  //                  Print("订单号为：",OrderTicket(),"的多单平仓失败",iGetErrorInf0());
  //                  }
  //                }
  //              else
  //                {
  //                double 比例=MathAbs(yl/(OrderProfit()+OrderSwap()+OrderCommission()));
  //                double 平仓手数=MathRound((OrderLots()*比例)/minlot)*minlot;
  //                if(平仓手数<minlot) 平仓手数=minlot;
  //                if(平仓手数>maxlot) 平仓手数=maxlot;  
  //                if(OrderClose(OrderTicket(),平仓手数,Bid,500))  return;
  //                return;
  //                }
  //              }
  //            }
  //          }
  //        }
  //      }
  //    }
  //  }
  }
//+------------------------------------------------------------------+
bool close_tic(int ticket_0)
  {
  if(OrderSelect(ticket_0,SELECT_BY_TICKET))
    {
    if(OrderType()<2)
      {
      if(OrderClose(OrderTicket(),OrderLots(),OrderType()==OP_BUY? MarketInfo(OrderSymbol(),MODE_BID) : MarketInfo(OrderSymbol(),MODE_ASK),500,clrRed)) 
        {Print("订单号为：",OrderTicket(),"的定单平仓成功 ");return(true);}
      else{Print("订单号为：",OrderTicket(),"的定单平仓失败 ",GetLastError());return(false);}
      }
    if(OrderType()>=2) 
      {
      if(OrderDelete(OrderTicket())) {Print("订单号为：",OrderTicket(),"的挂单删除成功 ");return(true);}
      else {Print("订单号为：",OrderTicket(),"的挂单删除失败 ",GetLastError());return(false);}
      }
    }
  return(false);
  }
//+------------------------------------------------------------------+
int price_tic(double &盈亏啊,double &手数啊,int type=-1,int magic=0)
  {
  int tic=0;
  double openprice=0;
  if(OrdersTotal()>0)
    for(int k=OrdersTotal()-1;k>=0;k--)
      if(OrderSelect(k,SELECT_BY_POS,MODE_TRADES)==true && OrderSymbol()==Symbol()) 
        if((magic==0 || OrderMagicNumber()==magic) && OrderType()<2)
          {
          if(OrderType()==OP_BUY && type<=0)
            {
            if(OrderProfit()+OrderSwap()+OrderCommission()<0 && openprice<OrderOpenPrice())                   {openprice=OrderOpenPrice();手数啊=OrderLots();盈亏啊=OrderProfit()+OrderSwap()+OrderCommission();tic=OrderTicket();}
            }
          if(OrderType()==OP_SELL && (type==1||type<0))
            {
            if(OrderProfit()+OrderSwap()+OrderCommission()<0 && (openprice>OrderOpenPrice() || openprice==0)) {openprice=OrderOpenPrice();手数啊=OrderLots();盈亏啊=OrderProfit()+OrderSwap()+OrderCommission();tic=OrderTicket();}
            }
          }
  return(tic);
  }
//+------------------------------------------------------------------+
double ma_angle()
  {
  if(MarketInfo(Symbol(),MODE_ASK)<=0 || MarketInfo(Symbol(),MODE_ASK)>=1000000) return(0);
  double angle=0;
  int index=0;
  double a0=iMA(Symbol(),均线角度的时间周期（current代表图表周期）,均线角度的均线参数,0,0,0,index+0);
  double a1=iMA(Symbol(),均线角度的时间周期（current代表图表周期）,均线角度的均线参数,0,0,0,index+1);
  double a2=iMA(Symbol(),均线角度的时间周期（current代表图表周期）,均线角度的均线参数,0,0,0,index+2);
  double a3=iMA(Symbol(),均线角度的时间周期（current代表图表周期）,均线角度的均线参数,0,0,0,index+3);
  double a4=iMA(Symbol(),均线角度的时间周期（current代表图表周期）,均线角度的均线参数,0,0,0,index+4);
  double angle1=(a0-a1);
  double angle2=(a1-a2);
  double angle3=(a2-a3);
  double angle4=(a3-a4);
  angle=angle1*0.4+angle2*0.3 +angle3*0.2+angle4*0.1;
  return(angle);
  }
//+------------------------------------------------------------------+
void kaicang()
  {
  tongji();
  if(ping>0) return;
  
  if(All_yk<0 && Buyyl >单向赢利多少金额对冲反向 && ma_angle()<0)  
    {
    close_对冲(1);
    }
  if(All_yk<0 && Sellyl>单向赢利多少金额对冲反向 && ma_angle()>0) 
    {
    close_对冲(0);
    }
  
  if(新策略_AllVol>0)
    {
    if(新策略_多==0 && buytime!=Time[0]) 
      {
      send(0,首单手数,"0_首单");
      buytime=Time[0];
      tongji();
      }
    if(新策略_空==0 && selltime!=Time[0]) 
      {
      send(1,首单手数,"0_首单");
      selltime=Time[0];
      tongji();
      }
    }
  if(AllBuy<多空最大持仓次数  && BuyHighest!=0  && 顺势加仓间距>0 && Close[1]>=BuyHighest+顺势加仓间距*Point && Ask>=BuyHighest+顺势加仓间距*Point && buytime!=Time[0])  
    {
    send(0,danliang("顺",Buyshun ),IntegerToString(Buyshun+1) +"_顺势"); 
    buytime=Time[0];
    tongji();
    }
  if(AllBuy<多空最大持仓次数  && BuyLowest!=0   && 逆势加仓间距>0 && Close[1]<=BuyLowest- 逆势加仓间距*Point && Ask<=BuyLowest- 逆势加仓间距*Point && buytime!=Time[0])  
    {
    send(0,danliang("逆",Buyni   ),IntegerToString(Buyni+1)   +"_逆势"); 
    buytime=Time[0];
    tongji();
    }
  if(AllSell<多空最大持仓次数 && SellHighest!=0 && 逆势加仓间距>0 && Close[1]>=SellHighest+逆势加仓间距*Point && Bid>=SellHighest+逆势加仓间距*Point && selltime!=Time[0])  
    {
    send(1,danliang("逆",Sellni  ),IntegerToString(Sellni+1)  +"_逆势"); 
    selltime=Time[0];
    tongji();
    }
  if(AllSell<多空最大持仓次数 && SellLowest!=0  && 顺势加仓间距>0 && Close[1]<=SellLowest-顺势加仓间距*Point && Bid<=SellLowest-顺势加仓间距*Point && selltime!=Time[0])   
    {
    send(1,danliang("顺",Sellshun),IntegerToString(Sellshun+1)+"_顺势"); 
    selltime=Time[0];
    tongji();
    }
  if(AllBuyLots!=0 && AllSellLots!=0 && MathAbs(AllBuyLots-AllSellLots)>一边与另一边手数差大于N补仓)
    {
    if(AllBuyLots>AllSellLots)  send(1,AllBuyLots-AllSellLots-一边与另一边手数差大于N补仓,"补仓"); 
    if(AllSellLots>AllBuyLots)  send(0,AllSellLots-AllBuyLots-一边与另一边手数差大于N补仓,"补仓"); 
    tongji();
    }
  }
//+------------------------------------------------------------------+
bool pingcang()
  {
  tongji();
  if((该魔术码的货币亏损金额>0 && All_yk<=-该魔术码的货币亏损金额) || ping==1)
    {
    ping=1;
    if(close()) {ping=0;Print("该魔术码货币对止损金额平仓");魔术码金额平仓时间=TimeCurrent();return(false);}
    }
  if((AllBuy+AllSell>0 && 账户亏损不分品种全平(账户亏损金额超限全清仓,账户亏损比例超限全清仓)) || ping==2)
    {
    ping=2;
    if(close()) {ping=0;Print("账户亏损不分品种全平");return(false);}
    }
  if((多空总赢利金额平仓>0 && All_yk>=多空总赢利金额平仓) || ping==3)
    {
    ping=3;
    if(close()) {ping=0;Print("多空总赢利金额平仓");return(false);}
    }
  if((All_yk>0 && 单向赢利多少金额对冲反向>0 && (Buyyl>单向赢利多少金额对冲反向 || Sellyl>单向赢利多少金额对冲反向)) || ping==4)
    {
    ping=4;
    if(close()) {ping=0;Print("单向赢利多少金额对冲反向");return(false);}
    }
  if(ping>0) return(false);
  return(true);
  }
//+------------------------------------------------------------------+
bool close(int type=2)
  {
  if(OrdersTotal()>0)
    {
    for(int k=OrdersTotal()-1; k>=0; k--)
      {
      if(OrderSelect(k,SELECT_BY_POS,MODE_TRADES)==true)
        {
        if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic)
          {
          if(OrderType()==OP_BUY  && (type==0 || type==2))
            {
            if(OrderClose(OrderTicket(),OrderLots(),Bid,500)) ;
            else
              {
              Print("订单号为：",OrderTicket(),"的多单平仓失败",iGetErrorInf0());
              }
            }
          if((OrderType()==2 || OrderType()==4) && (type==0 || type==2))
            {
            if(OrderDelete(OrderTicket()))
              {
              Print("订单号为：",OrderTicket(),"的挂单删除成功 ");
              }
            else
              {
              Print("订单号为：",OrderTicket(),"的挂单删除失败 ",iGetErrorInf0());
              }
            }
          if(OrderType()==OP_SELL && (type==1 || type==2))
            {
            if(OrderClose(OrderTicket(),OrderLots(),Ask,500)) ;
            else
              {
              Print("订单号为：",OrderTicket(),"的空单平仓失败",iGetErrorInf0());
              }
            }
          if((OrderType()==3 || OrderType()==5) && (type==1 || type==2))
            {
            if(OrderDelete(OrderTicket()))
              {
              Print("订单号为：",OrderTicket(),"的挂单删除成功 ");
              }
            else
              {
              Print("订单号为：",OrderTicket(),"的挂单删除失败 ",iGetErrorInf0());
              }
            }
          }
        }
      }
    }
   int shu=0;
   if(OrdersTotal()>0)
      for(int k=OrdersTotal()-1; k>=0; k--)
         if(OrderSelect(k,SELECT_BY_POS,MODE_TRADES)==true)
            if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic)
              {
               if((OrderType()==OP_BUY  || OrderType()==2 || OrderType()==4) && (type==0 || type==2))  shu++;
               if((OrderType()==OP_SELL || OrderType()==3 || OrderType()==5) && (type==1 || type==2))  shu++;
              }
   if(shu==0)  return(true);
   return(false);
  }
//+------------------------------------------------------------------+
bool 账户亏损不分品种全平(double N,double M)
  {       
  if(
    (N!=0 && AccountEquity()<AccountBalance() && MathAbs(AccountBalance()-AccountEquity()-自定义赠金)>MathAbs(N))
    ||
    (M!=0 && AccountEquity()<AccountBalance() && (1-AccountEquity()/AccountBalance())>(M/100))
    )  return(true);
  return(false);
  }
//+------------------------------------------------------------------+
void tongji()
  {
  Buyyl=0;Sellyl=0;
  All_yk=0;
  AllBuyLots=0;AllSellLots=0;
  AllBuy=0;AllSell=0;
  新策略_AllVol=0;新策略_多=0;新策略_空=0;
  BuyHighest=0;BuyLowest=0;SellHighest=0;SellLowest=0;
  Buyshun=0;Buyni=0;Sellshun=0;Sellni=0;
  if(OrdersTotal()>0)  
    {
    for(int k=OrdersTotal()-1;k>=0;k--)  
      {
      if(OrderSelect(k,SELECT_BY_POS,MODE_TRADES)==true)  
        {
        if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic)  
          {
          All_yk+=(OrderProfit()+OrderSwap()+OrderCommission());
          if(OrderType()<2 && (StringFind(OrderComment(),"_",0)!=-1 || StringFind(OrderComment(),"from",0)!=-1 || StringFind(OrderComment(),"补仓",0)!=-1))  新策略_AllVol++;
          if(StringFind(OrderComment(),"_",0)!=-1)
            {
            if(OrderType()==OP_BUY)
              {
              新策略_多++;
              if(BuyHighest<OrderOpenPrice())  
                {
                BuyHighest=OrderOpenPrice();
                if(StringFind(OrderComment(),"顺势",0)!=-1)
                  {
                  int p=StringFind(OrderComment(),"_",0);
                  Buyshun=StrToInteger(StringSubstr(OrderComment(),0,p)); 
                  }
                }
              if(BuyLowest>OrderOpenPrice() || BuyLowest==0)  
                {
                BuyLowest=OrderOpenPrice();
                if(StringFind(OrderComment(),"逆势",0)!=-1)
                  {
                  int p=StringFind(OrderComment(),"_",0);
                  Buyni=StrToInteger(StringSubstr(OrderComment(),0,p)); 
                  }
                }
              }
            if(OrderType()==OP_SELL)
              {
              新策略_空++;
              if(SellHighest<OrderOpenPrice())  
                {
                SellHighest=OrderOpenPrice();
                if(StringFind(OrderComment(),"逆势",0)!=-1 || StringFind(OrderComment(),"首单",0)!=-1)
                  {
                  int p=StringFind(OrderComment(),"_",0);
                  Sellni=StrToInteger(StringSubstr(OrderComment(),0,p)); 
                  }
                }
              if(SellLowest>OrderOpenPrice() || SellLowest==0)  
                {
                SellLowest=OrderOpenPrice();
                if(StringFind(OrderComment(),"顺势",0)!=-1 || StringFind(OrderComment(),"首单",0)!=-1)
                  {
                  int p=StringFind(OrderComment(),"_",0);
                  Sellshun=StrToInteger(StringSubstr(OrderComment(),0,p)); 
                  }
                }
              }
            }
          if(OrderType()==OP_BUY)   
            {
            Buyyl+=(OrderProfit()+OrderSwap()+OrderCommission());
            AllBuy++;
            AllBuyLots+=OrderLots();
            }
          if(OrderType()==OP_SELL)  
            {
            Sellyl+=(OrderProfit()+OrderSwap()+OrderCommission());
            AllSell++;
            AllSellLots+=OrderLots();
            }
          } 
        } 
      } 
    }
  }
//+------------------------------------------------------------------+
bool send(int fx_0,double danliang,string 注释)
  {
  double 单量=MathRound(danliang/minlot)*minlot;
  if(单量<minlot) 单量=minlot;
  if(单量>maxlot) 单量=maxlot;  
  int ticket=0;
  if(fx_0==0)
    {
     ticket=OrderSend(Symbol(),0,单量,Ask,500,0,0,注释,Magic,0,clrBlue);
    if(ticket>0){Print("多单开单成功"); }
    else {Print("多单开单失败。失败原因：",iGetErrorInf0());Sleep(500);}
    }
  if(fx_0==1)
    {
     ticket=OrderSend(Symbol(),1,单量,Bid,500,0,0,注释,Magic,0,clrRed);
    if(ticket>0){Print("空单开单成功");}
    else {Print("空单开单失败。失败原因：",iGetErrorInf0());Sleep(500);}
    }
  if(ticket>0) return(true);
  return(false);
  }
//+------------------------------------------------------------------+
double danliang(string 顺逆,int num)
  {
   double 倍数=0;
   double 最大手数=0; 
   double lots_0=0;
   if(顺逆=="顺")  {倍数=顺势加仓倍数;最大手数=顺势单次最大建仓手数;}
   if(顺逆=="逆")  {倍数=逆势加仓倍数;最大手数=逆势单次最大建仓手数;}
   lots_0=首单手数*MathPow(倍数,num+1);
   if(lots_0>最大手数) lots_0=最大手数;
   return(lots_0);  
  }  
//+------------------------------------------------------------------+
string iGetErrorInf0()
  {
   int myLastErrorMub=GetLastError();
   string myLastErrorStr;
   switch(myLastErrorMub)
     {
      case 0:myLastErrorStr="错误代码:#"+(string)0+",没有错误返回";break;
      case 1:myLastErrorStr="错误代码:#"+(string)1+",没有错误返回但结果不明";break;
      case 2:myLastErrorStr="错误代码:#"+(string)2+",一般错误";break;
      case 3:myLastErrorStr="错误代码:#"+(string)3+",无效交易参量";break;
      case 4:myLastErrorStr="错误代码:#"+(string)4+",交易服务器繁忙";break;
      case 5:myLastErrorStr="错误代码:#"+(string)5+",客户终端旧版本";break;
      case 6:myLastErrorStr="错误代码:#"+(string)6+",没有连接服务器";break;
      case 7:myLastErrorStr="错误代码:#"+(string)7+",没有权限";break;
      case 8:myLastErrorStr="错误代码:#"+(string)8+",请求过于频繁";break;
      case 9:myLastErrorStr="错误代码:#"+(string)9+",交易运行故障";break;
      case 64:myLastErrorStr="错误代码:#"+(string)64+",账户禁止";break;
      case 65:myLastErrorStr="错误代码:#"+(string)65+",无效账户";break;
      case 128:myLastErrorStr="错误代码:#"+(string)128+",交易超时";break;
      case 129:myLastErrorStr="错误代码:#"+(string)129+",无效价格";break;
      case 130:myLastErrorStr="错误代码:#"+(string)130+",无效停止";break;
      case 131:myLastErrorStr="错误代码:#"+(string)131+",无效交易量";break;
      case 132:myLastErrorStr="错误代码:#"+(string)132+",市场关闭";break;
      case 133:myLastErrorStr="错误代码:#"+(string)133+",交易被禁止";break;
      case 134:myLastErrorStr="错误代码:#"+(string)134+",资金不足";break;
      case 135:myLastErrorStr="错误代码:#"+(string)135+",价格改变";break;
      case 136:myLastErrorStr="错误代码:#"+(string)136+",开价";break;
      case 137:myLastErrorStr="错误代码:#"+(string)137+",经纪繁忙";break;
      case 138:myLastErrorStr="错误代码:#"+(string)138+",重新开价";break;
      case 139:myLastErrorStr="错误代码:#"+(string)139+",定单被锁定";break;
      case 140:myLastErrorStr="错误代码:#"+(string)140+",只允许看涨仓位";break;
      case 141:myLastErrorStr="错误代码:#"+(string)141+",过多请求";break;
      case 145:myLastErrorStr="错误代码:#"+(string)145+",因为过于接近市场，修改否定";break;
      case 146:myLastErrorStr="错误代码:#"+(string)146+",交易文本已满";break;
      case 147:myLastErrorStr="错误代码:#"+(string)147+",时间周期被经纪否定";break;
      case 148:myLastErrorStr="错误代码:#"+(string)148+",开单和挂单总数已被经纪限定";break;
      case 149:myLastErrorStr="错误代码:#"+(string)149+",当对冲备拒绝时,打开相对于现有的一个单置";break;
      case 150:myLastErrorStr="错误代码:#"+(string)150+",把为反FIFO规定的单子平掉";break;
      case 4000:myLastErrorStr="错误代码:#"+(string)4000+",没有错误";break;
      case 4001:myLastErrorStr="错误代码:#"+(string)4001+",错误函数指示";break;
      case 4002:myLastErrorStr="错误代码:#"+(string)4002+",数组索引超出范围";break;
      case 4003:myLastErrorStr="错误代码:#"+(string)4003+",对于调用堆栈储存器函数没有足够内存";break;
      case 4004:myLastErrorStr="错误代码:#"+(string)4004+",循环堆栈储存器溢出";break;
      case 4005:myLastErrorStr="错误代码:#"+(string)4005+",对于堆栈储存器参量没有内存";break;
      case 4006:myLastErrorStr="错误代码:#"+(string)4006+",对于字行参量没有足够内存";break;
      case 4007:myLastErrorStr="错误代码:#"+(string)4007+",对于字行没有足够内存";break;
      case 4008:myLastErrorStr="错误代码:#"+(string)4008+",没有初始字行";break;
      case 4009:myLastErrorStr="错误代码:#"+(string)4009+",在数组中没有初始字串符";break;
      case 4010:myLastErrorStr="错误代码:#"+(string)4010+",对于数组没有内存";break;
      case 4011:myLastErrorStr="错误代码:#"+(string)4011+",字行过长";break;
      case 4012:myLastErrorStr="错误代码:#"+(string)4012+",余数划分为零";break;
      case 4013:myLastErrorStr="错误代码:#"+(string)4013+",零划分";break;
      case 4014:myLastErrorStr="错误代码:#"+(string)4014+",不明命令";break;
      case 4015:myLastErrorStr="错误代码:#"+(string)4015+",错误转换(没有常规错误)";break;
      case 4016:myLastErrorStr="错误代码:#"+(string)4016+",没有初始化数组";break;
      case 4017:myLastErrorStr="错误代码:#"+(string)4017+",禁止调用DLL ";break;
      case 4018:myLastErrorStr="错误代码:#"+(string)4018+",数据库不能下载";break;
      case 4019:myLastErrorStr="错误代码:#"+(string)4019+",不能调用函数";break;
      case 4020:myLastErrorStr="错误代码:#"+(string)4020+",禁止调用智能交易函数";break;
      case 4021:myLastErrorStr="错误代码:#"+(string)4021+",对于来自函数的字行没有足够内存";break;
      case 4022:myLastErrorStr="错误代码:#"+(string)4022+",系统繁忙 (没有常规错误)";break;
      case 4050:myLastErrorStr="错误代码:#"+(string)4050+",无效计数参量函数";break;
      case 4051:myLastErrorStr="错误代码:#"+(string)4051+",无效参量值函数";break;
      case 4052:myLastErrorStr="错误代码:#"+(string)4052+",字行函数内部错误";break;
      case 4053:myLastErrorStr="错误代码:#"+(string)4053+",一些数组错误";break;
      case 4054:myLastErrorStr="错误代码:#"+(string)4054+",应用不正确数组";break;
      case 4055:myLastErrorStr="错误代码:#"+(string)4055+",自定义指标错误";break;
      case 4056:myLastErrorStr="错误代码:#"+(string)4056+",不协调数组";break;
      case 4057:myLastErrorStr="错误代码:#"+(string)4057+",整体变量过程错误";break;
      case 4058:myLastErrorStr="错误代码:#"+(string)4058+",整体变量未找到";break;
      case 4059:myLastErrorStr="错误代码:#"+(string)4059+",测试模式函数禁止";break;
      case 4060:myLastErrorStr="错误代码:#"+(string)4060+",没有确认函数";break;
      case 4061:myLastErrorStr="错误代码:#"+(string)4061+",发送邮件错误";break;
      case 4062:myLastErrorStr="错误代码:#"+(string)4062+",字行预计参量";break;
      case 4063:myLastErrorStr="错误代码:#"+(string)4063+",整数预计参量";break;
      case 4064:myLastErrorStr="错误代码:#"+(string)4064+",双预计参量";break;
      case 4065:myLastErrorStr="错误代码:#"+(string)4065+",数组作为预计参量";break;
      case 4066:myLastErrorStr="错误代码:#"+(string)4066+",刷新状态请求历史数据";break;
      case 4067:myLastErrorStr="错误代码:#"+(string)4067+",交易函数错误";break;
      case 4099:myLastErrorStr="错误代码:#"+(string)4099+",文件结束";break;
      case 4100:myLastErrorStr="错误代码:#"+(string)4100+",一些文件错误";break;
      case 4101:myLastErrorStr="错误代码:#"+(string)4101+",错误文件名称";break;
      case 4102:myLastErrorStr="错误代码:#"+(string)4102+",打开文件过多";break;
      case 4103:myLastErrorStr="错误代码:#"+(string)4103+",不能打开文件";break;
      case 4104:myLastErrorStr="错误代码:#"+(string)4104+",不协调文件";break;
      case 4105:myLastErrorStr="错误代码:#"+(string)4105+",没有选择定单";break;
      case 4106:myLastErrorStr="错误代码:#"+(string)4106+",不明货币对";break;
      case 4107:myLastErrorStr="错误代码:#"+(string)4107+",无效价格";break;
      case 4108:myLastErrorStr="错误代码:#"+(string)4108+",无效定单编码";break;
      case 4109:myLastErrorStr="错误代码:#"+(string)4109+",不允许交易";break;
      case 4110:myLastErrorStr="错误代码:#"+(string)4110+",不允许多单";break;
      case 4111:myLastErrorStr="错误代码:#"+(string)4111+",不允许空单";break;
      case 4200:myLastErrorStr="错误代码:#"+(string)4200+",定单已经存在";break;
      case 4201:myLastErrorStr="错误代码:#"+(string)4201+",不明定单属性";break;
      case 4202:myLastErrorStr="错误代码:#"+(string)4202+",定单不存在";break;
      case 4203:myLastErrorStr="错误代码:#"+(string)4203+",不明定单类型";break;
      case 4204:myLastErrorStr="错误代码:#"+(string)4204+",没有定单名称";break;
      case 4205:myLastErrorStr="错误代码:#"+(string)4205+",定单坐标错误";break;
      case 4206:myLastErrorStr="错误代码:#"+(string)4206+",没有指定子窗口";break;
      case 4207:myLastErrorStr="错误代码:#"+(string)4207+",定单一些函数错误";break;
      case 4250:myLastErrorStr="错误代码:#"+(string)4250+",错误设定发送通知到队列中";break;
      case 4251:myLastErrorStr="错误代码:#"+(string)4251+",无效参量- 空字符串传递到SendNotification()函数";break;
      case 4252:myLastErrorStr="错误代码:#"+(string)4252+",无效设置发送通知(未指定ID或未启用通知)";break;
      case 4253:myLastErrorStr="错误代码:#"+(string)4253+",通知发送过于频繁";break;
      default :myLastErrorStr="错误代码:NULL";break;
     }
   return(myLastErrorStr);
  }
//+------------------------------------------------------------------+
void yuancelue()
  {
   yuan_tongji();
   if(新策略_AllVol>0) return;
   if(buyTTlots>0.0 && sellTTlots / buyTTlots>3.0 && sellTTlots - buyTTlots>0.2)
     {
      buylossthansell = true ;
     }
   else
     {
      buylossthansell = false ;
     }
   if(sellTTlots>0.0 && buyTTlots / sellTTlots>3.0 && buyTTlots - sellTTlots>0.2)
     {
      sellllossthanbuy = true ;
     }
   else
     {
      sellllossthanbuy = false ;
     }
   if(IsTradeAllowed() == false || IsExpertEnabled() == false || IsStopped() || MarketInfo(Symbol(),MODE_SPREAD)>MaxSpread)
     {
      buyonoff = false ;
      sellonoff = false ;
     }
   else
     {
      buyonoff = true ;
      sellonoff = true ;
     }
     
         if(buyprofit>StopProfit)
           {
            Print("Buy Profit ",buyprofit);
            CloseOrders(1);
            return;
           }
         if(sellprofit>StopProfit)
           {
            Print("Sell Profit ",sellprofit);
            CloseOrders(-1);
            return;
           } 
     
     
   Totalprofit = buyprofit + sellprofit ;
   if(((Money!=0.0 && Totalprofit>Money) || Money==0.0))
     {
      UseSetp = true ;
     }
   if(Money!=0.0 && Totalprofit<=Money)
     {
      UseSetp = false ;
     }
   if(((OpenMode == 1 && barcontronl != iTime(NULL,TimeZone,0)) || OpenMode == 2 || OpenMode == 3))
     {
      if(buystopcount == 0 && buyonoff)
        {
         if(buyordercount == 0)
           {
            price = NormalizeDouble(FirstStep * Point() + Ask,Digits()) ;
           }
         else
           {
            if(UseSetp)
              {
               price = NormalizeDouble(MinDistance * Point() + Ask,Digits()) ;
              }
            if(UseSetp == false && Money!=0.0)
              {
               price = NormalizeDouble(TwoMinDistance * Point() + Ask,Digits()) ;
              }
            if(price<NormalizeDouble(maxbuyprice - Step * Point(),Digits()) && UseSetp)
              {
               price = NormalizeDouble(Step * Point() + Ask,Digits()) ;
              }
            if(price<NormalizeDouble(maxbuyprice - TwoStep * Point(),Digits()) && UseSetp == false && Money!=0.0)
              {
               price = NormalizeDouble(TwoStep * Point() + Ask,Digits()) ;
              }
           }
         if((buyordercount == 0 || (minbuyprice!=0.0 && price>=NormalizeDouble(Step * Point() + minbuyprice,Digits()) && buylossthansell && UseSetp)
             || (minbuyprice!=0.0 && price>=NormalizeDouble(TwoStep * Point() + minbuyprice,Digits()) && buylossthansell && UseSetp == false && Money!=0.0)
             || (maxbuyprice!=0.0 && price<=NormalizeDouble(maxbuyprice - Step * Point(),Digits()) && UseSetp)
             || (maxbuyprice!=0.0 && price<=NormalizeDouble(maxbuyprice - TwoStep * Point(),Digits()) && UseSetp == false && Money!=0.0)))
           {
            if(buyordercount == 0)
              {
               lots = lot ;
              }
            else
              {
               lots = NormalizeDouble(lot * MathPow(K_Lot,buyordercount) + buyordercount * PlusLot,2) ;
              }
               // Print("总_da_65=",总_da_65,"  总_da_66=",总_da_66,"  临_da_123=",临_da_123,"  总_da_63=",总_da_63,"  临_da_123=",临_da_123);
               if(buyordercount >= 1  || buyordercount == 0)
                 {
                  //增加一个最后订单时间控制
                  if((/*(TimeCurrent() - 临_in_133 >= sleep && OpenMode == 2) ||*/ OpenMode == 3 || OpenMode == 1))
                    {
                     if(((minbuyprice!=0.0 && price>=NormalizeDouble(Step * Point() + minbuyprice,Digits()) && buylossthansell && UseSetp)
                         || (minbuyprice!=0.0 && price>=NormalizeDouble(TwoStep * Point() + minbuyprice,Digits()) && buylossthansell && UseSetp == false && Money!=0.0)))
                       {
                        string 注释="SS";
                        if(buyordercount == 4)  {lots =首单手数 ;注释="0_首单";}
                        int tick = OrderSend(Symbol(),OP_BUYSTOP,lots,price,500,0.0,0.0,注释,Magic,0,Blue) ;
                        if(tick > 0)
                          {
                           Print(Symbol() + "开单成功，订单编号:" + DoubleToString(tick,0));
                          }
                        else
                          {
                           Print(Symbol() + "开单失败，错误代码 = ",GetLastError());
                          }
                       }
                     else
                       {
                        string 注释="NN";
                        if(buyordercount == 4)  {lots =首单手数 ;注释="0_首单";}
                        int tick = OrderSend(Symbol(),OP_BUYSTOP,lots,price,500,0.0,0.0,注释,Magic,0,Blue) ;
                        if(tick > 0)
                          {
                           Print(Symbol() + "开单成功，订单编号:" + DoubleToString(tick,0));
                          }
                        else
                          {
                           Print(Symbol() + "开单失败，错误代码 = ",GetLastError());
                          }
                       }
                    }
                 }
           }
         else
           {
            Comment("Lot ",DoubleToString(lots,2));
           }
        }

   if(sellstopcount == 0  && sellonoff)
     {
      if(sellorderscount == 0)
        {
         price = NormalizeDouble(Bid - FirstStep * Point(),Digits()) ;
        }
      else
        {
         if(UseSetp)
           {
            price = NormalizeDouble(Bid - MinDistance * Point(),Digits()) ;
           }
         if(UseSetp == false)
           {
            price = NormalizeDouble(Bid - TwoMinDistance * Point(),Digits()) ;
           }
         if(price<NormalizeDouble(Step * Point() + minsellprice,Digits()) && UseSetp)
           {
            price = NormalizeDouble(Bid - Step * Point(),Digits()) ;
           }
         if(price<NormalizeDouble(TwoStep * Point() + minsellprice,Digits()) && UseSetp == false && Money!=0.0)
           {
            price = NormalizeDouble(Bid - TwoStep * Point(),Digits()) ;
           }
        }
      if(sellorderscount == 0 || (maxsellprice!=0.0 && price<=NormalizeDouble(maxsellprice - Step * Point(),Digits()) && sellllossthanbuy && UseSetp) 
          || (maxsellprice!=0.0 && price<=NormalizeDouble(maxsellprice - TwoStep * Point(),Digits()) && sellllossthanbuy && UseSetp == false && Money!=0.0) 
          || (minsellprice!=0.0 && price>=NormalizeDouble(Step * Point() + minsellprice,Digits()) && UseSetp) 
          || (minsellprice!=0.0 && price>=NormalizeDouble(TwoStep * Point() + minsellprice,Digits()) && UseSetp == false && Money!=0.0) )
        {
         if(sellorderscount == 0)
           {
            lots = lot ;
           }
         else
           {
            lots = NormalizeDouble(lot * MathPow(K_Lot,sellorderscount) + sellorderscount * PlusLot,2) ;
           }
            // Print("总_da_65=",总_da_65,"  总_da_66=",总_da_66,"  临_da_123=",临_da_123,"  总_da_63=",总_da_63,"  临_da_123=",临_da_123);
            if(sellorderscount >= 1 || sellorderscount == 0)
              {
               if((/*(TimeCurrent() - 临_in_150 >= sleep && OpenMode == 2) ||*/ OpenMode == 3 || OpenMode == 1))
                 {
                  if(((maxsellprice!=0.0 && price<=NormalizeDouble(maxsellprice - Step * Point(),Digits()) && sellllossthanbuy && UseSetp)
                      || (maxsellprice!=0.0 && price<=NormalizeDouble(maxsellprice - TwoStep * Point(),Digits()) && sellllossthanbuy && UseSetp == false && Money!=0.0)))
                    {
                     string 注释="SS";
                     if(sellorderscount == 4)  {lots =首单手数 ;注释="0_首单";}
                     int tick = OrderSend(Symbol(),OP_SELLSTOP,lots,price,500,0.0,0.0,注释,Magic,0,Red) ;
                     if(tick > 0)
                       {
                        Print(__FUNCTION__,  ": "+ Symbol()+ " 开单成功，订单编号:"+ DoubleToString(tick,0));
                       }
                     else
                       {
                        Print(__FUNCTION__,": 开单失败，错误代码 = ",GetLastError());
                       }
                    }
                  else
                    {
                     string 注释="NN";
                     if(sellorderscount == 4)  {lots =首单手数 ;注释="0_首单";}
                     int tick = OrderSend(Symbol(),OP_SELLSTOP,lots,price,500,0.0,0.0,注释,Magic,0,Red) ;
                     if(tick > 0)
                       {
                        Print(__FUNCTION__,  ": "+ Symbol()+ " 开单成功，订单编号:"+ DoubleToString(tick,0));
                       }
                     else
                       {
                        Print(__FUNCTION__,": 开单失败，错误代码 = ",GetLastError());
                       }
                    }
                 }
              }
        }
      else
        {
         Comment("Lot ",DoubleToString(lots,2));
        }
     }
   barcontronl = iTime(NULL,TimeZone,0) ;
  }
//----------------------------------------------------------------
//修改买单价格
//+---------------------------------------------------------------
if(buystopprice!=0.0 && buyonoff)
  {
   if(buyordercount == 0)
     {
      price = NormalizeDouble(FirstStep * Point() + Ask,Digits()) ;
     }
   if(UseSetp && buyordercount > 0)
     {
      price = NormalizeDouble(MinDistance * Point() + Ask,Digits()) ;
     }
   if(UseSetp == false && buyordercount > 0 && Money!=0.0)
     {
      price = NormalizeDouble(TwoMinDistance * Point() + Ask,Digits()) ;
     }
   if(NormalizeDouble(buystopprice - StepTrallOrders * Point(),Digits())>price && (((price<=NormalizeDouble(maxbuyprice - Step * Point(),Digits())
         || maxbuyprice==0.0 || (buylossthansell && buyordercount == 0) || price>=NormalizeDouble(Step * Point() + minbuyprice,Digits())
         || price<=NormalizeDouble(maxbuyprice - Step * Point(),Digits())) && UseSetp) || ((price<=NormalizeDouble(maxbuyprice - TwoStep * Point(),Digits())
               || maxbuyprice==0.0 || (buylossthansell && buyordercount == 0) || price>=NormalizeDouble(TwoStep * Point() + minbuyprice,Digits())
               || price<=NormalizeDouble(maxbuyprice - TwoStep * Point(),Digits())) && UseSetp == false && Money!=0.0)))
     {
      if(!(OrderModify(buystopticket,price,0.0,0.0,0,White)))
        {
         Print("Error ",GetLastError(),"   Order Modify Buy   OOP ",buystopprice,"->",price);
        }
      else
        {
         Print("Order Buy Modify   OOP ",buystopprice,"->",price);
        }
     }
  }
//----------------------------------------------------------------
//修改卖单价格
//+---------------------------------------------------------------
if(sellstopprice!=0.0 && sellonoff)
  {
   if(sellorderscount == 0)
     {
      price = NormalizeDouble(Bid - FirstStep * Point(),Digits()) ;
     }
   if(UseSetp && sellorderscount > 0)
     {
      price = NormalizeDouble(Bid - MinDistance * Point(),Digits()) ;
     }
   if(UseSetp == false && sellorderscount > 0 && Money!=0.0)
     {
      price = NormalizeDouble(Bid - TwoMinDistance * Point(),Digits()) ;
     }
   if(NormalizeDouble(StepTrallOrders * Point() + sellstopprice,Digits())<price && (((price>=NormalizeDouble(Step * Point() + minsellprice,Digits())
         || minsellprice==0.0 || (sellllossthanbuy && sellorderscount == 0) || price<=NormalizeDouble(maxsellprice - Step * Point(),Digits())
         || price>=NormalizeDouble(Step * Point() + minsellprice,Digits())) && UseSetp) || ((price>=NormalizeDouble(TwoStep * Point() + minsellprice,Digits())
               || minsellprice==0.0 || (sellllossthanbuy && sellorderscount == 0) || price<=NormalizeDouble(maxsellprice - TwoStep * Point(),Digits())
               || price>=NormalizeDouble(TwoStep * Point() + minsellprice,Digits())) && UseSetp == false && Money!=0.0)))
     {
      if(!(OrderModify(sellstopticket,price,0.0,0.0,0,White)))
        {
         Print("Error ",GetLastError(),"   Order Modify Sell   OOP ",sellstopprice,"->",price);
        }
      else
        {
         Print("Order Sell Modify   OOP ",sellstopprice,"->",price);
        }
     }
  }
  }
//+------------------------------------------------------------------+
void yuan_tongji()
  {
   buySScount=0;
   sellSScount=0;
   buySScount1 = 0;
   sellSScount1 = 0;
   sellprofit = 0.0 ;
   buyprofit = 0.0 ;
   buyTTlots = 0.0 ;
   sellTTlots = 0.0 ;
   buyordercount = 0 ;
   sellorderscount = 0 ;
   buystopcount = 0 ;
   sellstopcount = 0 ;
   buystopticket = 0 ;
   sellstopticket = 0 ;
   minbuyprice = 0.0 ;
   maxbuyprice = 0.0 ;
   minsellprice = 0.0 ;
   maxsellprice = 0.0 ;
   buystopprice = 0.0 ;
   sellstopprice = 0.0 ;
   sellcost = 0.0 ;
   buycost = 0.0 ;
   buypriceaverage = 0.0 ;
   sellpriceaverage = 0.0 ;
   price = 0.0 ;
   lots = 0.0 ;
   count1 = 0 ;
   checkprofit = 0.0 ;
   UseSetp = false ;
   for(count1 = 0 ; count1 < OrdersTotal() ; count1++)
     {
      if(!(OrderSelect(count1,SELECT_BY_POS,MODE_TRADES)) || OrderSymbol() != Symbol() || Magic != OrderMagicNumber())
         continue;
      if(OrderType() == OP_BUYSTOP)
        {
         buystopcount++;
         if((minbuyprice<NormalizeDouble(OrderOpenPrice(),Digits()) || minbuyprice==0.0))
           {
            minbuyprice = NormalizeDouble(OrderOpenPrice(),Digits()) ;
           }
         buystopticket = OrderTicket() ;
         buystopprice = NormalizeDouble(OrderOpenPrice(),Digits()) ;
        }
      if(OrderType() == OP_SELLSTOP)
        {
        sellstopcount++;
         if((maxsellprice>NormalizeDouble(OrderOpenPrice(),Digits()) || maxsellprice==0.0))
           {
            maxsellprice = NormalizeDouble(OrderOpenPrice(),Digits()) ;
           }
         sellstopticket = OrderTicket() ;
         sellstopprice = NormalizeDouble(OrderOpenPrice(),Digits()) ;
        }
      if(OrderType() == OP_BUY)
        {
         if(StringFind(OrderComment(),"NN",0)!=-1 || StringFind(OrderComment(),"SS",0)!=-1)  buyordercount++;
         buyTTlots += OrderLots() ;
         buycost += NormalizeDouble(OrderOpenPrice(),Digits()) * OrderLots() ;
         if((minbuyprice<NormalizeDouble(OrderOpenPrice(),Digits()) || minbuyprice==0.0))
           {
            minbuyprice = NormalizeDouble(OrderOpenPrice(),Digits()) ;
           }
         if((maxbuyprice>NormalizeDouble(OrderOpenPrice(),Digits()) || maxbuyprice==0.0))
           {
            maxbuyprice = NormalizeDouble(OrderOpenPrice(),Digits()) ;
           }
         buyprofit += OrderProfit() + OrderSwap() + OrderCommission() ;
        }
      if(OrderType() == OP_SELL)
        {
         if(StringFind(OrderComment(),"NN",0)!=-1 || StringFind(OrderComment(),"SS",0)!=-1)  sellorderscount++;
         sellTTlots += OrderLots() ;
         sellcost += NormalizeDouble(OrderOpenPrice(),Digits()) * OrderLots() ;
         if((maxsellprice>NormalizeDouble(OrderOpenPrice(),Digits()) || maxsellprice==0.0))
           {
            maxsellprice = NormalizeDouble(OrderOpenPrice(),Digits()) ;
           }
         if((minsellprice<NormalizeDouble(OrderOpenPrice(),Digits()) || minsellprice==0.0))
           {
            minsellprice = NormalizeDouble(OrderOpenPrice(),Digits()) ;
           }
         sellprofit += OrderProfit() + OrderSwap() + OrderCommission() ;
        }
     }
  }
//+------------------------------------------------------------------+
int CloseOrders (int type)                  //按type平单，0为平多空，1只平多，-1只平空
{
   int         k,j;
   bool        closeorder;
   int         i;
//----------------------------
   j=0;
   closeorder = true ;
   while (j < 10)
   {
      for (i = OrdersTotal() - 1 ; i >= 0 ; i = i - 1)
      {
         if ( !(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) || OrderSymbol() != Symbol() || OrderMagicNumber() != Magic )   continue;
         if ( OrderType() == 0 && ( type == 1 || type == 0 ) )
         {
            closeorder = OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(Bid,Digits()),500,clrBlue) ;
            if ( closeorder )
            {
                Print(Symbol() + "平仓成功，订单编号:" + IntegerToString(OrderTicket()),"     ",TimeToString(TimeCurrent(),TIME_SECONDS));
            }
            else
            {
                Print(Symbol() + "平仓失败，错误代码 = ",GetLastError());
            }
         }
         if ( OrderType() == 1 && ( type == -1 || type == 0 ) )
         {
            closeorder = OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(Ask,Digits()),500,clrRed) ;
            if ( closeorder )
            {
                Print(Symbol() + "平仓成功，订单编号:" + IntegerToString(OrderTicket()),"     ",TimeToString(TimeCurrent(),TIME_SECONDS));
            }
            else
            {
                Print(Symbol() + "平仓失败，错误代码 = ",GetLastError());
            }
         }
         if ( OrderType() == 4 && ( type == 1 || type == 0 ) )
         {
            closeorder = OrderDelete(OrderTicket(),0xFFFFFFFF) ;
         }
         if ( OrderType() == 5 && ( type == -1 || type == 0 ) )
         {
            closeorder = OrderDelete(OrderTicket(),0xFFFFFFFF) ;
         }
      }
      k = 0 ;
      for (i = 0 ; i < OrdersTotal() ; i = i + 1)
      {
         if ( !(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) || OrderSymbol() != Symbol() || OrderMagicNumber() != Magic )   continue;
         if ( ( OrderType() == 4 || OrderType() == 0 ) && ( type == 1 || type == 0 ) )
         {
            k = k + 1;
         }
         if ( ( OrderType() == 5 || OrderType() == 1 ) && ( type ==  -1 || type == 0 ) )  
         {
            k = k + 1;
         }
      }
      if ( k == 0 )    break;
      j++;
      if(j>8)
      {
         Print(Symbol(),"平仓超过8次"); 
         return(0);
      }
      Sleep(1000); 
      RefreshRates(); 
      continue;
   }
   return(1); 
}